package be.castanea.client.model;

import com.jme.bounding.BoundingBox;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.shape.Box;

/**
 * Castanea
 * 2009
 * @author Geert van Leemputten, Steven Rymenans, Bart Van Hooydonck
 */
public class Mob extends Node {

    private World world;
    private int maxSpeed;
    private Movement movement;
    protected Spatial model;    

    public Mob(String name, Vector3f location, Quaternion rotation, Movement movement) {
        super(name);

        loadModel();
        model.setModelBound(new BoundingBox());
        model.updateModelBound();
        this.attachChild(model);
        this.setModelBound(new BoundingBox());
        this.updateModelBound();

        this.setLocalTranslation(location);
        this.maxSpeed = 50;
        if (rotation != null) {
            this.setLocalRotation(rotation);
        }
        this.movement = (movement != null) ? movement : new Movement();        
    }

    public Mob(String name, Vector3f location) {
        this(name, location, null, null);      
    }

    public void loadModel() {
        Box box = new Box(name, new Vector3f(0f, 0.4f, 0f), 0.2f, 0.8f, 0.2f);
        box.setRandomColors();
        model = box;
    }
    
    public int getMaxSpeed() {
        return maxSpeed;
    }

    public Movement getMovement() {
        return movement;
    }

    public void setMovement(Movement movement) {
        this.movement = movement;
    }

    public void registerWorld(World world) {
        this.world = world;
        this.world.attachChild(this);
        this.world.updateWorldBound();
        this.setLocalTranslation(getWorldTranslation());
        this.setLocalRotation(getWorldRotation());
    }

    public void update(float interpolation) {
        // speeds
        float forwardDistance = movement.getForwardSpeed() * interpolation;
        float sidewayDistance = movement.getSidewaySpeed() * interpolation;
        if (forwardDistance != 0 && sidewayDistance != 0) {
            forwardDistance /= 2;
            sidewayDistance /= 2;
        }
        float turnSpeedDistance = movement.getTurnSpeed() * interpolation;

        // move
        Vector3f location = getWorldTranslation();
        location = location.addLocal(getLocalRotation().getRotationColumn(2).multLocal(forwardDistance));
        location = location.addLocal(getLocalRotation().getRotationColumn(0).multLocal(sidewayDistance));
        location.setY(World.getInstance().getHeight(location));
        setLocalTranslation(location);

        // turn
        Quaternion turning = new Quaternion();
        turning.fromAngleAxis(turnSpeedDistance, Vector3f.UNIT_Y);
        setLocalRotation(turning.mult(getLocalRotation()));
    }
}